package com.cbgolf.oa.activity.permission;

import static com.cbgolf.oa.util.AnimaUtil.stopLoading;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.PermissionAdapter;
import com.cbgolf.oa.base.BaseActivity;
import com.cbgolf.oa.entity.PermissionsBean;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.NetUtils;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.user.UserData;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.DensityUtil;
import com.cbgolf.oa.util.DialogUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import com.cbgolf.oa.widget.pick.PickValueView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * @author Created by Administrator on 2017/8/27.
 */

public class PermissionCheckActivity extends BaseActivity implements
    PermissionAdapter.onPermissionListener, SwipeRefreshLayout.OnRefreshListener {

  //top
  @ViewInject(R.id.topBack_ll)
  private View topBack;
  @ViewInject(R.id.title_tv)
  private TextView topTitle;
  @ViewInject(R.id.topRight_iv)
  private ImageView topRightIv;
  //body
  @ViewInject(R.id.a_permission_refreshlayout)
  private SwipeRefreshLayout refreshLayout;
  @ViewInject(R.id.a_permission_listview)
  private ListView listView;
  @ViewInject(R.id.g_error_ll)
  private View errorView;
  @ViewInject(R.id.g_error_tv)
  private TextView errorTv;
  @ViewInject(R.id.g_error_reload_tv)
  private TextView reLoadTv;
  @ViewInject(R.id.g_error_loading_tv)
  private TextView loadingTv;
  //var
  private List<PermissionsBean> listData = new ArrayList<>();
  private PermissionAdapter adapter;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.a_permission_check);
  }

  @Override
  protected void findViews() {
    x.view().inject(this);
  }

  @Override
  protected void setViews() {
    topTitle.setText("权限审批");
    topRightIv.setVisibility(View.VISIBLE);
    topRightIv.setImageResource(R.drawable.jilu);
    adapter = new PermissionAdapter(context, false, this);
    listView.setAdapter(adapter);

    getData();
  }

//    private String textToken = "f2bdc4df-96da-4827-86ad-cc7375bd2da1";

  private void getData() {
    if (!Util.isNetWorkConnected()) {
      showError(NONET);
      return;
    }
    String url = WebAPI.permission_select_get;
    showLoading();
    Web.getOK(url, new NetCallBack(response -> {
      if (NetUtils.SUCCESS != response.statusCode) {
        showError(NETERROR);
        return;
      }
      if (Util.isNull(response.result)) {
        showError(NODATA);
        return;
      }
      List<PermissionsBean> list = DataUtil.getList(response, PermissionsBean.class);
      listData.clear();
      if (!Util.listIsNull(list)) {
        showData();
        listData.addAll(list);
        adapter.setData(listData);
        adapter.upDataUI();
        return;
      }
      showError(NODATA);
    }));
  }

  private void showLoading() {
    if (!refreshLayout.isRefreshing()) {
      AnimaUtil.showLoading(context, loadingTv);
    }
  }

  private void showData() {
    stopLoading();
    if (refreshLayout.isRefreshing()) {
      refreshLayout.setRefreshing(false);
    }
    errorView.setVisibility(View.GONE);
    refreshLayout.setVisibility(View.VISIBLE);
  }

  private final int NONET = 1;
  private final int NETERROR = 2;
  private final int NODATA = 3;

  private void showError(int type) {
    stopLoading();
    if (refreshLayout.isRefreshing()) {
      refreshLayout.setRefreshing(false);
    }
//        if(isAllowOrRefush) {
//            isAllowOrRefush = false;
//            return;
//        }
    if (listData.size() > 0) {
      switch (type) {
        case NONET:
          Util.showNoNet();
          break;
        case NETERROR:
          Util.showNetError();
          break;
        case NODATA:
          Util.showNoData();
          break;
        default:
          break;
      }
      return;
    }
    refreshLayout.setVisibility(View.GONE);
    errorView.setVisibility(View.VISIBLE);
    reLoadTv.setVisibility(View.VISIBLE);
    switch (type) {
      case NONET:
        errorTv.setText(getResources().getString(R.string.no_net));
        break;
      case NETERROR:
        errorTv.setText(getResources().getString(R.string.net_error));
        break;
      case NODATA:
        errorTv.setText("很抱歉，暂无审批内容");
        break;
      default:
        break;
    }


  }

  @Override
  protected void setListener() {
    topBack.setOnClickListener(v -> finish());
    topRightIv.setOnClickListener(v -> mStartActivity(PermissionCheckHistoryActivity.class));
    reLoadTv.setOnClickListener(v -> getData());
    refreshLayout.setOnRefreshListener(this);

  }

  @Override
  protected void onKeyBack() {
    finish();
  }


  @Override
  public void allow(final int position) {
    String title = "温馨提示";
    String msg = "您是否确认允许该操作，\n一经允许不可修改。";
    DialogUtil.showMsgDialog(context, title, msg, () -> {
      String id = listData.get(position).id;
      allowOrRefuse(id, true, "");
    });

  }


  @Override
  public void refuse(int position) {
    String id = listData.get(position).id;
    showWheelDialog(id);

  }

  public String causeStr;
  private String[] cause =
      new String[]{"不符合条件", "不符合流程", "不符合申请"};

  private void showWheelDialog(final String id) {
    final Dialog dialog = new Dialog(context, R.style.mDialog);
    View view = context.getLayoutInflater().inflate(R.layout.dialog_wheel, null);
    View layout = view.findViewById(R.id.dialog_layout);
    TextView titleTv = (TextView) view.findViewById(R.id.dialog_title_tv);
    titleTv.setText("审批时效");
    TextView cancelTv = (TextView) view.findViewById(R.id.dialog_cancel_tv);
    TextView subMitTv = (TextView) view.findViewById(R.id.dialog_submit_tv);
    PickValueView wheel = (PickValueView) view.findViewById(R.id.dialog_wheel);
    wheel.setValueData(cause, cause[1]);
    causeStr = cause[1];
    DialogUtil.setWidthHeight(layout, DensityUtil.getScreenWidth() * 2 / 3, 0);
    AutoUtil.auto(view);
    dialog.setContentView(view);

    wheel.setOnSelectedChangeListener(
        (view1, leftValue, middleValue, rightValue) -> causeStr = leftValue.toString());
    cancelTv.setOnClickListener(v -> {
      dialog.cancel();
      dialog.dismiss();
    });
    subMitTv.setOnClickListener(v -> {
      dialog.cancel();
      dialog.dismiss();
      allowOrRefuse(id, false, causeStr);
    });
    dialog.show();
  }


  private void allowOrRefuse(String id, boolean allow, String cause) {
    if (!Util.isNetWorkConnected()) {
      Util.showNoNet();
      return;
    }
    if (Util.isNull(id)) {
      Util.showNetError();
      return;
    }
    String url = WebAPI.permission_allow_or_refuse_put + "/" + id;
    Map<String, Object> map = new HashMap<>();
    JSONObject json = new JSONObject();
    try {
      json.put("audit", allow);
      json.put("refuseReason", Util.isNull(cause) ? "" : cause);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    String token = UserData.getUser() == null ? "" : UserData.getUser().getToken();
    map.put("dto", json);
    map.put("token", token);
    AnimaUtil.showLoading(context);
    Web.putjsonOk(url, map, new NetCallBack(response -> {
      stopLoading();
      if (NetUtils.SUCCESS != response.statusCode) {
        Util.show(response.errorMsg);
        return;
      }
      getData();
    }));


  }


  @Override
  public void onRefresh() {
    getData();
  }
}
